package cn.cvs.web;


import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.util.Constants;
import cn.cvs.util.DataTransfer;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.cvs.util.Constants.pageSize;

@Controller
public class SysUserController {

    @Resource
    SysUserService sysUserService;
    @Resource
    SysRoleService sysRoleService;

    @RequestMapping(value = {"/toLogin","/"})
    public String toLogin(){
        System.out.println("执行控制器toLogin方法");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(@RequestParam String account, @RequestParam String password, Model model, HttpSession session){
        SysUser sysUser = sysUserService.queryUser(account, password);
        if (sysUser != null){
            //登录成功
            //将登录用户保存到Session中
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "frame";
        }else{
            //登录失败
            //绑定错误消息，跳转到登录页面
            model.addAttribute("error","用户名或密码错误！");
            return "forward:/toLogin";
        }
    }



    //异常处理方法
    //当前控制器SysUserController抛出的异常
    //都会交个这个方法处理
    @ExceptionHandler(value = {Exception.class})
    public String exceptionMethod(Exception e, Model model){
            //打印异常的堆栈信息
            e.printStackTrace();
            model.addAttribute("exception",e);
            return "sysError";
    }




    @RequestMapping("/sys/toMain")
    public String toMain(){
        return "frame";
    }

    //根据输入算输出
    //输入：入参 客户端(页面...)传递给后台参数
    //输出：出参 后台传递给客户端(页面...)的数据
    //对于前后台不分离的系统 这种数据就放在作用域中
    //我们用的是jsp那么出参就是el表达式中的数据
    @RequestMapping("/sys/user/list")
    public String list(@RequestParam(value = "queryRealName",required = false) String realName,
                       @RequestParam(value = "queryRoleId",required = false) Integer roleId,
                       @RequestParam(value="pageIndex",required = false,defaultValue ="1") Integer pageNo, Model model){
        //出参queryRealName
        model.addAttribute("queryRealName",realName);
        //出参queryRoleId
        model.addAttribute("queryRoleId",roleId);
        //出参roleList所有的角色
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("roleList",sysRoles);
        //出参userList用户列表
        List<SysUser> sysUsers = sysUserService.querySysUsers(realName, roleId, pageNo, pageSize);
        model.addAttribute("userList",sysUsers);

        //出参 totalCount 总记录数
        int count = sysUserService.queryCount(realName, roleId);
        model.addAttribute("totalCount",count);
        //出参 currentPageNo当前页码等于pageNo
        model.addAttribute("currentPageNo",pageNo);
        //出参 totalPageCount总页数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(Constants.pageSize);
        pageSupport.setTotalCount(count);
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "sysUser/list";
    }



    //跳转到添加用户界面
    @RequestMapping("/sys/user/toAdd")
    public String toAddUser(@ModelAttribute("sysUser") SysUser sysUser, Model model) {
        //角色列表
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("sysRoles",sysRoles);
        //model.addAttribute("sysUser",new SysUser());
        return "sysUser/add";
    }


    //添加用户 上传单文件
    /*@PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session, Model model,
                          @RequestParam(value = "idPic",required = false) MultipartFile idPic,
                          HttpServletRequest request) {
        //登录判断
        SysUser loginUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if (loginUser == null){
            //没有登录
            model.addAttribute("error","请登录后操作");
            return "login";
        }
        //查看后台验证的结果
        if(bindingResult.hasErrors()){
            //校验出错误，不能通过
            //回数据添加的页面，会自动带上错误消息
            throw new RuntimeException("数据校验错误！");
        }

        //上传文件的核心代码
        //图片命名规则
        //时间戳(毫秒数)_图片的原名
        String  saveFileName= System.currentTimeMillis()+"_"+idPic.getOriginalFilename();
        //保存到服务器上的路径
        String dirPath=
        request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadFiles");
                //服务器根目录的物理路径

        //服务器根目录/statics/uploadFiles/...
        File dir = new File(dirPath);
        if (!dir.exists()){
            //如果这个目录不存在就创建
            dir.mkdirs();
        }
        File saveFile = new File(dir,saveFileName);
        //idPic.transferTo(new File("服务器保存文件的路径"));
        try {
            idPic.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("图片上传失败",e);
        }
        //向数据库保存图片的信息
        //保存一个逻辑路径，方便在其他地方引用
        String idPicPath =File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
        sysUser.setIdPicPath(idPicPath);






        //创建时间
        sysUser.setCreatedTime(new Date());
        //创建人id
        sysUser.setCreatedUserId(loginUser.getId());
        int i = sysUserService.addUser(sysUser);
        if (i>0){
            //添加用户成功
            //重定向回用户列表
            return "redirect:/sys/user/list";
        }else {
            //添加用户失败
            throw new RuntimeException("添加用户失败！");
        }

    }*/
    //添加用户 上传多文件
    @PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session, Model model,
                          @RequestParam(value = "attaches",required = false) MultipartFile[] attaches,
                          HttpServletRequest request) {
        //登录判断
        SysUser loginUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if (loginUser == null){
            //没有登录
            model.addAttribute("error","请登录后操作");
            return "login";
        }
        //查看后台验证的结果
        if(bindingResult.hasErrors()){
            //校验出错误，不能通过
            //回数据添加的页面，会自动带上错误消息
            throw new RuntimeException("数据校验错误！");
        }


        for (int i = 0; i < attaches.length; i++) {
            //上传文件的核心代码
            //图片命名规则
            //时间戳(毫秒数)_图片的原名
            String  saveFileName= System.currentTimeMillis()+"_"+attaches[i].getOriginalFilename();
            //保存到服务器上的路径
            String dirPath=
                    request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadFiles");
            //服务器根目录的物理路径
            //D:\ide总文件夹\ssmdemo-kf01\target\spring-mvn-prex\
            //服务器根目录/statics/uploadFiles/...
            File dir = new File(dirPath);
            if (!dir.exists()){
                //如果这个目录不存在就创建
                dir.mkdirs();
            }
            File saveFile = new File(dir,saveFileName);
            //idPic.transferTo(new File("服务器保存文件的路径"));
            try {
                attaches[i].transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("图片上传失败",e);
            }
            //向数据库保存图片的信息
            //保存一个逻辑路径，方便在其他地方引用
            String PicPath =File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;

            if (i==0){
                //设置身份照
                sysUser.setIdPicPath(PicPath);
            }else{
                //设置工作照
                sysUser.setWorkPicPath(PicPath);
            }

        }








        //创建时间
        sysUser.setCreatedTime(new Date());
        //创建人id
        sysUser.setCreatedUserId(loginUser.getId());
        int i = sysUserService.addUser(sysUser);
        if (i>0){
            //添加用户成功
            //重定向回用户列表
            return "redirect:/sys/user/list";
        }else {
            //添加用户失败
            throw new RuntimeException("添加用户失败！");
        }

    }


    //跳转到修改页面
    @RequestMapping("/sys/user/toUpdate")
    public String toUpdateUser(@RequestParam("uid") Integer id, Model model){
        //查询id对应的用户
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser" ,sysUser);
        //角色列表
        List<SysRole> sysRoles = sysRoleService.queryAllRoles();
        model.addAttribute("sysRoles",sysRoles);
        return "sysUser/update";
    }

    //修改用户
    @PostMapping("/sys/user/update")
    public String updateUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session){
        //登录验证
        SysUser loginUser =
                (SysUser)session.getAttribute(Constants.USER_SESSION);
        if (loginUser == null){
            throw new RuntimeException("请登录后操作！");
        }

        //检查后台校验的结果
        if (bindingResult.hasErrors()){
            return "sysUser/update";
        }

        //修改时间
        sysUser.setUpdatedTime(new Date());
        //修改人id
        sysUser.setUpdatedUserId(loginUser.getId());

        int i = sysUserService.updateUser(sysUser);
        if (i>0){
            //修改成功
            //重定向到用户列表
          return "redirect:/sys/user/list";
        }else {
            //修改失败
            throw new RuntimeException("修改失败！请稍后再试");
        }
    }
    //查看用户信息
    //@PathVariable 定义路径变量
    @GetMapping("/sys/user/view/{uid}")
    public String viewUser(@PathVariable("uid") Integer id, Model model){
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";
    }



    //检查account是否重名
    @ResponseBody//标识这是一个ajax发送的异步请求
    @GetMapping("/sys/user/userExist")
    public Object userExists(String account){
            //返回值Map
        Map<String, Object> resultMap = new HashMap();
        if (StringUtils.isEmpty(account)){
            resultMap.put("exist","-1");
            resultMap.put("msg","账户不能为空");
            return JSON.toJSONString(resultMap);
        }
        try {
            int count = sysUserService.queryUserExist(account);
            if (count >0){
                //不可用
                resultMap.put("exist","1");
            }else{
                //可用
                resultMap.put("exist","0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("exist","-1");
            resultMap.put("msg",e.getMessage());
        }
        return JSON.toJSONString(resultMap);
    }



    //异步查看用户信息
    @ResponseBody//异步请求
    @GetMapping("/sys/user/{uid}/view")
    public Object viewUser2(@PathVariable("uid") Integer id){
        //返回值对象
        DataTransfer<SysUser> dto = new DataTransfer<>();
        try {
            if (id == null) {
                dto.setStatus("failed");
                return JSON.toJSONString(dto);
            }
            SysUser sysUser = sysUserService.queryById(id);
            if (sysUser == null) {
                dto.setStatus("nodata");
                return JSON.toJSONString(dto);
            }
            //查询成功
            dto.setStatus("ok");
            dto.setData(sysUser);
            return JSON.toJSONString(dto);
        }catch(Exception e){
            e.printStackTrace();
            dto.setStatus("failed");
            return JSON.toJSONString(dto);
        }
    }


    //异步删除用户
    @ResponseBody//异步请求加这个
    @DeleteMapping("/sys/user/{uid}")
    public Object deleteUser(@PathVariable("uid")Integer id, HttpSession session, HttpServletRequest request){
        //返回值对象
        Map<String,Object> resultMap = new HashMap<>();
        try {
            //登录检查
            SysUser loginUser=
            (SysUser)session.getAttribute(Constants.USER_SESSION);
            if (loginUser==null){
                resultMap.put("delResult","noLogin");
                resultMap.put("msg","请登录后操作");
                return JSON.toJSONString(resultMap);
            }
            if (id==null){
                resultMap.put("delResult","error");
                resultMap.put("msg","参数错误！");
                return JSON.toJSONString(resultMap);
            }
            //非管理员不能删除
            if(loginUser.getRoleId()!=1){
                resultMap.put("delResult","notadmin");
                resultMap.put("msg","非管理员不能做删除操作！");
                return JSON.toJSONString(resultMap);
            }

            //依据id查询要删除的用户
            SysUser sysUser = sysUserService.queryById(id);
            if (sysUser == null) {
                resultMap.put("delResult","notexist");
                return JSON.toJSONString(resultMap);
            }

            //不能删除管理员
            if (sysUser.getRoleId()==1){
                resultMap.put("delResult","deladmin");
                resultMap.put("msg","不能删除管理员！");
                return JSON.toJSONString(resultMap);
            }

            //删除
            int count = sysUserService.deleteUser(id, request);
            if (count > 0) {
                //1删除成功
                resultMap.put("delResult","true");
            }else{
                //0删除失败
                resultMap.put("delResult","false");
            }
            return JSON.toJSONString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("delResult","error");
            resultMap.put("msg","系统繁忙，请稍后再试!");
            return JSON.toJSONString(resultMap);
        }
    }
    //登出
    @GetMapping("/logout")
    public String logout() {
        return "login";
    }
}
